import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  // 处理token
  mutationSetToken(state, token) {
    state.token = token
    setToken(token)
  },
  mutationRemoveToken(state) {
    state.token = null
    // 需要把cookies里的token删除
    removeToken()
  },
  // 处理用户信息
  mutationSetUserInfo(state, res) {
    state.userInfo = res
  },
  mutationRemoveUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async actionLogin(store, data) {
    const result = await login(data)
    // console.log(result)
    // 提交给mutation对token进行修改（state只能由mutation进行修改）
    store.commit('mutationSetToken', result)
    localStorage.setItem('loginTime', Date.now())
  },
  // 获取用户信息
  async actionGetUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserDetail(res.userId)
    // console.log(29, res)
    store.commit('mutationSetUserInfo', { ...res, ...detail })
  },
  // 登出
  async actionLogout(store) {
    await store.commit('mutationRemoveToken')
    await store.commit('mutationRemoveUserInfo')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
